package com.minimalist.basic.config.filter;

import com.alibaba.druid.spring.boot3.autoconfigure.properties.DruidStatProperties;
import com.minimalist.basic.config.exception.BusinessException;
import jakarta.servlet.*;
import org.apache.catalina.util.ParameterMap;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author 11987
 */
@Component
@WebFilter(filterName = "DruidFilter", urlPatterns = "/myDruid/doLogin")
public class DruidFilter implements Filter {
    @Autowired
    DruidStatProperties druidStatProperties;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse
            , FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 只拦截自动登录的代理方法
        if (!request.getRequestURL().toString().contains("/myDruid/doLogin")) {
            filterChain.doFilter(request, response);
            return;
        }
        // 获取到参数，并通过反射去添加在配置文件中的Druid账号密码
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap instanceof org.apache.catalina.util.ParameterMap) {
            try {
                Field field = ParameterMap.class.getDeclaredField("locked");
                field.setAccessible(true);
                field.setBoolean(parameterMap, false);
                parameterMap.put("loginUsername", new String[]{
                        druidStatProperties.getStatViewServlet().getLoginUsername()});
                parameterMap.put("loginPassword", new String[]{
                        druidStatProperties.getStatViewServlet().getLoginPassword()});
                field.setBoolean(parameterMap, true);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                throw new BusinessException(e.getMessage());
            }
            // 转发到实际的Druid登录路径上
            request.getRequestDispatcher("/druid/submitLogin").forward(request, response);
        }
        filterChain.doFilter(request, response);
    }
}
